package com.shop.servlet.client;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.shop.comment.Constants;
import com.shop.config.AlipayConfig;
import com.shop.config.JedisConfig;
import com.shop.entity.Goods;
import com.shop.entity.User;
import com.shop.entity.VO.BuyVo;
import com.shop.entity.VO.CarVo;
import com.shop.entity.VO.GoodsParamVo;
import com.shop.service.GoodsService;
import com.shop.service.GoodsServiceImpl;
import com.shop.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "GoodsServlet",urlPatterns = "/GoodsServlet")
public class GoodsServlet extends HttpServlet {
	GoodsService service = new GoodsServiceImpl();
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if(action==null || action.equals("")){
			goodsList(request, response); //商品列表
		}else{
			switch (action){
				case "addCar": //添加到购物车
					addGoodsCar(request, response);
					break;
				case "buy":
					buy(request, response);
					break;
			}
		}

	}

	//结算
	private void buy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type"); //付款方式
		String addressId = request.getParameter("addressId"); //收货地址编号

		//添加订单
	    List<CarVo> carVoList =	(List<CarVo> )request.getSession().getAttribute("carList");
	    User user =  (User)request.getSession().getAttribute("loginUser");
		BuyVo vo = new BuyVo();
		vo.setAddressId(Integer.valueOf(addressId));
		vo.setPayType(Integer.valueOf(type));
		vo.setAccount(user.getAccount());
		vo.setList(carVoList);
		String orderNo = vo.getOrderNo();

		//清空购物车
		JedisConfig redeis = new JedisConfig();
		//String car = "744-1_736-3_742-1"; //商品编号-数量
		redeis.delete(Constants.RedisInfo.LOGIN_USER_CAR+user.getId());
		request.getSession().removeAttribute("carList");
		switch (type){
			case Constants.PayType.USER_MONEY_PAY: //余额
				moneypay(orderNo, request, response);
				break;
			case Constants.PayType.ARRIVAL_GOODS_PAY: //货到付款
				break;
			case Constants.PayType.ALI_PAY: //支付宝
				alibabaPay(orderNo,"100",response);
				break;
		}
		//页面跳转
		service.buy(vo);
	}

	//余额支付
	public void moneypay(String orderNo,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("orderNo",orderNo);
		request.setAttribute("payType",Constants.PayType.USER_MONEY_PAY);
		request.getRequestDispatcher("client/buycar/BuyCar_Three.jsp").forward(request, response);
	}

	//支付宝支付
	public void alibabaPay(String orderNo,String amount,HttpServletResponse response){
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);

		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

		//商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = orderNo;
		//付款金额，必填
		String total_amount = amount;
		//订单名称，必填
		String subject = "测试";
		//商品描述，可空
		String body = "";

		alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
				+ "\"total_amount\":\""+ total_amount +"\","
				+ "\"subject\":\""+ subject +"\","
				+ "\"body\":\""+ body +"\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

		// form表单生产
		String form = "";
		try {
			// 调用SDK生成表单
			form = alipayClient.pageExecute(alipayRequest).getBody();
			response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
			response.getWriter().write(form);//直接将完整的表单html输出到页面
			response.getWriter().flush();
			response.getWriter().close();
		} catch (AlipayApiException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//商品列表+分页
	public void goodsList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String page = request.getParameter("page");//页数
		String level = request.getParameter("level");//分类
		String id = request.getParameter("id");//类型编号

		int currentPage = page==null ? 1: Integer.valueOf(page);
		Integer lv = level==null ? null : Integer.valueOf(level);
		Integer classifyId = id==null ? null : Integer.valueOf(id);

		//操作
		PageUtil<Goods> pageUtil = new PageUtil<>();
		pageUtil.setCurrentPage(currentPage);


		GoodsParamVo paramVo = new GoodsParamVo(pageUtil.getBeginIndex(),lv,classifyId);
		List<Goods> list = service.findGoodByPage(paramVo);

		//数据封装
		pageUtil.setList(list);

		//页面跳转
		request.setAttribute("pageInfo", pageUtil);
		request.getRequestDispatcher("client/goods/BrandList.jsp").forward(request, response);
	}

	//添加到购物车
	public void addGoodsCar(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String goodsId = request.getParameter("goodsId");
		int id = Integer.valueOf(goodsId);
		//将商品添加到购物车==》判断商品是否已存在购物车中
		Object object = request.getSession().getAttribute("carList");
		//遍历
		boolean isExist = false;
		List<CarVo> list = null;
		if(object != null) {
			list = (List<CarVo>) object;
			for (CarVo tmp : list) {
				if (tmp.getGoods().getId() == id) {
					tmp.setCount(tmp.getCount() + 1);
					isExist = true;
				}
			}
		}else{
			list = new ArrayList<CarVo>();
		}
		//不存在
		if(!isExist) {
			Goods goods = service.findById(id);
			CarVo tmp = new CarVo(1, goods);
			list.add(tmp); //添加到购物车
		}
		//刷新购物车中的数据
		request.getSession().setAttribute("carList",list);
		//数据持久化操作==》将购物车中的数据写入数据库 / 写入Cookie / 写入缓存 ==>待完成
		User loginUser = (User)request.getSession().getAttribute("loginUser");
		addCar(list,loginUser.getId());
		//响应
		String jsonTmp = JSON.toJSONString(list);
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(jsonTmp);
		out.close();
	}

	/**
	 * 添加到购物车 ==》持久化操作
	 */
	public void addCar(List<CarVo> list,Integer userId){
		String tmp = "";
		for (CarVo vo : list)
		{
			tmp += vo.getGoods().getId()+"-"+vo.getCount()+"_";
		}
		tmp = tmp.substring(0,tmp.length()-1);
		//存入到缓存中
		JedisConfig redeis = new JedisConfig();
		//String car = "744-1_736-3_742-1"; //商品编号-数量
		redeis.set(Constants.RedisInfo.LOGIN_USER_CAR+userId,tmp);
	}
}
